package org.kjtc.weChatUtil;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.util.HttpURLConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

public class HttpJsonClient {
	private static Logger log = Logger.getLogger(HttpJsonClient.class);


	/**
	 * 图片服务器请求
	 * @param url
	 * @param json
	 * @return
	 */
	public static Map<String, String> imagePostJson(String url, Map<String, String> param) {

		Map<String, String> map = new HashMap<String, String>();
		map.put("status", "2");
		HttpPost post = new HttpPost(url + "/Upload");
		DefaultHttpClient httpClient = new DefaultHttpClient();
		try {
			List<NameValuePair> formParams = new ArrayList<NameValuePair>();
			if (param != null && param.size() != 0) {
				for (Iterator<String> it = param.keySet().iterator(); it.hasNext();) {
					String key = it.next();
					String value = param.get(key);
					formParams.add(new BasicNameValuePair(key, value));
				}
			}
			UrlEncodedFormEntity ueEntity = new UrlEncodedFormEntity(formParams, "utf-8");

			post.setEntity(ueEntity);

			HttpResponse httpResponse = httpClient.execute(post);
			if (httpResponse != null && httpResponse.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = httpResponse.getEntity();
				map.put("status", "1");
				map.put("result", EntityUtils.toString(entity).replaceAll("\"", ""));
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
		return map;
	}


	/**
	 * 方法描述:post发送json
	 *
	 * @param url
	 * @param json
	 * @return  JSONObject    status: 1 正常  2：服务调用失败
	 */
	public static JSONObject postJson(String url, JSONObject json) {

		log.info("链接云服务:" + url);
		DefaultHttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
		HttpPost post = post(url, json);

		JSONObject returnJson = new JSONObject();
		try {
			HttpResponse httpResponse = httpClient.execute(post);
	         int httpCode = httpResponse.getStatusLine().getStatusCode();
	         if (httpCode == HttpURLConnection.HTTP_OK && httpResponse != null) {
	             returnJson = JSONObject.fromObject(EntityUtils.toString(httpResponse.getEntity()));
	             returnJson.put("status", 1);
	         } else {
	        	 returnJson.put("status", 2);
	         }
 		} catch (Exception e) {
 			returnJson.put("status", 2);
 		} finally {
			httpClient.getConnectionManager().shutdown();
		}

		return returnJson;
	}
	/**
	 * 方法描述:get
	 *
	 * @param url
	 * @param url
	 * @return  JSONObject    status: 1 正常  2：服务调用失败
	 */
	public static JSONObject get(String url) {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		JSONObject returnJson = new JSONObject();
		HttpGet get = new HttpGet(url);
		try {
			httpClient.getParams().setParameter("http.protocol.content-charset", "UTF-8");
			HttpResponse response = httpClient.execute(get);

	         int httpCode = response.getStatusLine().getStatusCode();
	         if (httpCode == HttpURLConnection.HTTP_OK&&response!=null) {
		     		HttpEntity entity = response.getEntity();
		     		String charset = EntityUtils.getContentCharSet(entity);
		     		try {
		     			returnJson.put("body", EntityUtils.toString(entity));
		     		} catch (ParseException e) {
		     			returnJson.put("status", 2);
		     			e.printStackTrace();
		     		} catch (IOException e) {
		     			returnJson.put("status", 2);
		     			e.printStackTrace();
		     		}
		     		returnJson.put("status", 1);
	         } else {
	        	 returnJson.put("status", 2);
	         }
         } catch (ClientProtocolException e) {
        	 returnJson.put("status", 2);
 		} catch (IOException e) {
 			returnJson.put("status", 2);
 		} finally {
			httpClient.getConnectionManager().shutdown();
		}
		return returnJson;
	}
	//返回string
	public static String getUrlForString(String url){
        String result = null;
        try {
            // 根据地址获取请求
            DefaultHttpClient httpClient = new DefaultHttpClient();
            httpClient.getParams().setParameter("http.protocol.content-charset", "UTF-8");
            HttpGet request = new HttpGet(url);
            // 通过请求对象获取响应对象
            HttpResponse response = httpClient.execute(request);

            // 判断网络连接状态码是否正常(0--200都数正常)
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result= EntityUtils.toString(response.getEntity());
            }
        } catch (Exception e) {
        	return  null;
        }
        return result;
    }


	private static HttpPost post(String url, JSONObject json){
		HttpPost httpost = new HttpPost(url);
		try {

			StringEntity se = new StringEntity(json.toString(), "UTF-8");
	        se.setContentType("application/json");
			 httpost.setEntity(se);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return httpost;
	}
}
